/**
 * 
 */
package fhq.hcmute.modernshopping.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import fhq.hcmute.modernshopping.ProjectUtil;
import fhq.hcmute.modernshopping.R;
import fhq.hcmute.modernshopping.activities.ScanQrCodeActivity;
import fhq.hcmute.modernshopping.adapter.Product;

/**
 * @author: Hien Nguyen Le
 * @emai: hien.nguyenle.it@gmail.com
 * 
 */
public class ShoppingInfo extends Fragment {

	private TextView txt_TotalCost;
	private TextView txt_ProductQuantity;
	private TextView btn_ScanQrCode;
	private View root;
	private Context context;
	public static final int SHOPPING_REQUEST_CODE = 0;
	public static final int SHOPPING_RESULT_CODE = 1;
	private static ShoppingInfo instance = null;

	private ShoppingInfo() {
	}

	public static ShoppingInfo getInstance() {
		if (instance == null) {
			instance = new ShoppingInfo();
		}
		return instance;
	}

	public ShoppingInfo setContext(Context context) {
		instance.context = context;
		return instance;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		root = inflater.inflate(R.layout.fragment_shopping_info, container,
				false);
		init();
		return root;
	}

	public void updateView() {
		ShoppingListProduct instance = ShoppingListProduct.getInstance();
		txt_TotalCost.setText(ProjectUtil.formatCurrency(instance
				.getTotalPrice()) + getString(R.string.curency));
		txt_ProductQuantity.setText(instance.getTotalQuanlity()
				+ getString(R.string.product));
	}

	private void init() {
		txt_TotalCost = (TextView) root.findViewById(R.id.txt_total_cost);
		txt_ProductQuantity = (TextView) root
				.findViewById(R.id.txt_product_quantity);
		btn_ScanQrCode = (TextView) root.findViewById(R.id.btn_scan_qrcode);
		btn_ScanQrCode.setOnClickListener(onBtnScanQrCode);
	}

	private View.OnClickListener onBtnScanQrCode = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(context, ScanQrCodeActivity.class);
			intent.putExtra(ScanQrCodeActivity.SCAN_QRCODE_KEY,
					R.layout.activity_shopping);
			startActivityForResult(intent, SHOPPING_REQUEST_CODE);
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == SHOPPING_REQUEST_CODE) {
			if (resultCode == SHOPPING_RESULT_CODE) {
				Product product = (Product) data
						.getSerializableExtra(ScanQrCodeActivity.SCAN_QRCODE_RESULT);
				ShoppingListProduct.getInstance().addProduct(product);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
